﻿using AutoMapper;
using Chat.EntityFrameworkCore;
using Cx.NetCoreUtils.Exceptions;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;
using Xiao.Application.Dto.App;
using Xiao.Code.Entities.App;
using Xiao.EntityFrameworkCore.Core;
using Xiao.EntityFrameworkCore.Repository;

namespace Xiao.Application.Services.App
{
    public interface IProgramVersionService
    {
        /// <summary>
        /// 获取版本信息
        /// </summary>
        /// <param name="Identification"></param>
        /// <returns></returns>
        Task<ProgramVersionDto> GetProgramVersion(string Identification);
        /// <summary>
        /// 创建或更新版本信息
        /// </summary>
        /// <param name="program"></param>
        /// <returns></returns>
        Task<Guid> CreateProgramVersion(ProgramVersionDto program);
    }
    public class ProgramVersionService : BaseService<ProgramVersion>, IProgramVersionService
    {
        private readonly IMapper _mapper;
        public ProgramVersionService
            (
            IMapper mapper,
            IUnitOfWork<MasterDbContext> unitOfWork,
            IMasterDbRepositoryBase<ProgramVersion> currentRepository) 
            : base(unitOfWork, currentRepository)
        {
            _mapper = mapper;
        }

        public async Task<Guid> CreateProgramVersion(ProgramVersionDto program)
        {
            var programVersion =await currentRepository.FindAll(a => a.Identification == program.Identification).FirstOrDefaultAsync();
            if(programVersion == null)
            {
                programVersion = _mapper.Map<ProgramVersion>(program);
                programVersion = await currentRepository.AddAsync(programVersion);
            }
            else
            {
                program.Id = programVersion.Id;
                _mapper.Map(program, programVersion);
                currentRepository.Update(programVersion);
            }
            await unitOfWork.SaveChangesAsync();
            return programVersion.Id;
        }

        public async Task<ProgramVersionDto> GetProgramVersion(string Identification)
        {
            var data =await currentRepository.FindAll(a => a.Identification == Identification)
                .AsNoTracking()
                .FirstOrDefaultAsync();
            if (data == null) throw new BusinessLogicException("版本更新信息不存在");
            return _mapper.Map<ProgramVersionDto>(data);
        }
    }
}
